
import os
import sys
import time
import cPickle
import StringIO
import traceback

from dexen.system import constants, exceptions
from dexen.system.client import rpc_api
from dexen.user.libs import server_api, gui_api

looper_api = None

def process_once(func):
    if looper_api.has_script_input():
        inds = looper_api.download_live_individuals()
        results = func(inds)
    else:
        results = func()
    
    if results is not None:
        looper_api.upload_individuals(results)
        

def loop_task(schema_name, pop_name, script_name, file_name, function_name, url, 
              run_type, state, console_q, graph_q, script_id):
    global looper_api
    server_api._set_attributes(url, schema_name, pop_name, script_name)
    
    sys.path.append(os.path.join(constants.TEMP_SCHEMA_DIR, schema_name))    
    #prev_path = os.getcwd()
    os.chdir(os.path.join(constants.TEMP_SCHEMA_DIR, schema_name))    

    gui_api.graph_queue = graph_q
    gui_api.script_id = script_id
    
    module = __import__(file_name, fromlist=[""])
    func = getattr(module, function_name)
    
    sys.stdout = StringIO.StringIO()

    looper_api = rpc_api.LooperAPI(url, schema_name, pop_name, script_name)
    
    if run_type == constants.LOOPED:
        while state.value == constants.RUNNING:
            try:
                process_once(func)
            except exceptions.ScriptStoppedException, (instance):
                print instance.parameter
            except:
                print "Exception in", script_name
                print sys.exc_info()
                traceback.print_tb(sys.exc_traceback, file=sys.stdout)
            console_q.put(sys.stdout.getvalue())
            sys.stdout = StringIO.StringIO()
    elif run_type == constants.ONCE:
        process_once(func)
        console_q.put(sys.stdout.getvalue())

    state.value = constants.STOPPED
    return

